// pages/index/index.js
const app = getApp()
const { sceneAPI, deviceAPI } = require('../../utils/api.js')

Page({
  data: {
    currentTime: '',
    // 统计数据
    onlineDevices: 0,
    activeDevices: 0,
    energyUsage: '12.5',
    securityStatus: false,
    allLightsOn: false,
   // 天气信息
  weatherInfo: {
    temperature: '26',
    condition: '晴朗',
    conditionIcon: '/images/icons/sunny.png',
    feelsLike: '28',
    humidity: '65',
    windSpeed: '2.5',
    pressure: '1013',
    aqi: '35',
    aqiLevel: 'excellent',
    aqiDescription: '优',
    //MQTT
    mqttConnected: false,
    connectionStatus: '连接中...'
  },

  
    // 快捷场景数据
  quickScenes: [
    {
      id: 'home',
      name: '回家模式',
      description: '温馨回家体验',
      icon: '/images/icons/home-scene.png',
      background: '/images/scenes/home-bg.jpg',
      activeBackground: '/images/scenes/home-bg-active.jpg', // 激活状态的背景
      isActive: false,
      isFavorite: true
    },
    {
      id: 'sleep',
      name: '睡眠模式',
      description: '舒适睡眠环境',
      icon: '/images/icons/sleep-scene.png',
      background: '/images/scenes/sleep-bg.jpg',
      activeBackground: '/images/scenes/sleep-bg-active.jpg',
      isActive: false,
      isFavorite: true
    },
    {
      id: 'away',
      name: '离家模式',
      description: '安全节能离家',
      icon: '/images/icons/away-scene.png',
      background: '/images/scenes/away-bg.jpg',
      activeBackground: '/images/scenes/away-bg-active.jpg',
      isActive: false,
      isFavorite: false
    },
    {
      id: 'entertainment',
      name: '娱乐模式',
      description: '家庭影院体验',
      icon: '/images/icons/entertainment-scene.png',
      background: '/images/scenes/entertainment-bg.jpg',
      activeBackground: '/images/scenes/entertainment-bg-active.jpg',
      isActive: false,
      isFavorite: false
    }
  ],
    
    // 快捷设备数据
    quickDevices: [],
    
    // 房间概览数据
    roomOverview: [],
    
    // 智能建议数据
    suggestions: [
      {
        id: 1,
        title: '节能建议',
        description: '客厅空调温度可调至26°C更节能',
        action: 'adjust_ac'
      },
      {
        id: 2,
        title: '安防提醒',
        description: '您已2小时未开启安防模式',
        action: 'enable_security'
      }
    ],
    
    activatingScene: false,
    activatingSceneName: '',
    
    // 天气信息
    weatherInfo: {
      temperature: '26',
      condition: '晴朗',
      humidity: '65',
      airQuality: '优'
    }
  },
// 加载天气信息
async loadWeatherInfo() {
  try {
    // 模拟天气API调用
    const weatherData = await this.mockWeatherAPI()
    this.setData({
      weatherInfo: weatherData
    })
  } catch (error) {
    console.error('加载天气信息失败:', error)
  }
},

// 模拟天气API
mockWeatherAPI() {
  return new Promise((resolve) => {
    setTimeout(() => {
      const conditions = [
        { name: '晴朗', icon: '/images/icons/sunny.png' },
        { name: '多云', icon: '/images/icons/cloudy.png' },
        { name: '小雨', icon: '/images/icons/rainy.png' },
        { name: '阴天', icon: '/images/icons/overcast.png' },
        { name: '雾', icon: '/images/icons/foggy.png' }
      ]
      
      const aqiLevels = [
        { aqi: '25', level: 'excellent', desc: '优' },
        { aqi: '65', level: 'good', desc: '良' },
        { aqi: '105', level: 'moderate', desc: '轻度污染' },
        { aqi: '150', level: 'poor', desc: '中度污染' }
      ]
      
      const randomCondition = conditions[Math.floor(Math.random() * conditions.length)]
      const randomAqi = aqiLevels[Math.floor(Math.random() * aqiLevels.length)]
      
      resolve({
        temperature: (20 + Math.floor(Math.random() * 15)).toString(),
        condition: randomCondition.name,
        conditionIcon: randomCondition.icon,
        feelsLike: (22 + Math.floor(Math.random() * 10)).toString(),
        humidity: (50 + Math.floor(Math.random() * 30)).toString(),
        windSpeed: (1 + Math.random() * 5).toFixed(1),
        pressure: (1000 + Math.floor(Math.random() * 30)).toString(),
        aqi: randomAqi.aqi,
        aqiLevel: randomAqi.level,
        aqiDescription: randomAqi.desc
      })
    }, 1000)
  })
},
  onLoad() {
    this.updateTime()
    this.loadDeviceData()
     // 监听 MQTT 连接状态
     app.globalData.mqttClient.onConnectionChange((connected, error) => {
      this.setData({
        mqttConnected: connected,
        connectionStatus: connected ? '已连接' : (error ? '连接失败' : '连接中...')
      })
    })
    
    // 设置定时器每秒更新时间
    this.timeInterval = setInterval(() => {
      this.updateTime()
    }, 1000)
    
    // 监听设备状态变化
    this.onDeviceStatusChange = this.onDeviceStatusChange.bind(this)
  },
// 手动控制设备
controlDevice(deviceId, command) {
  const success = app.globalData.mqttClient.reportDeviceData({
    [deviceId]: command
  })

  if (success) {
    wx.showToast({ title: '指令发送成功', icon: 'success' })
  } else {
    wx.showToast({ title: '指令发送失败', icon: 'error' })
  }
},

// 重新连接
reconnectMQTT() {
  app.connectToOneNET()
  wx.showToast({ title: '重新连接中...', icon: 'loading' })
},


  onShow() {
    this.loadDeviceData()
    this.loadWeatherInfo()
  },

  onUnload() {
    // 清除定时器
    if (this.timeInterval) {
      clearInterval(this.timeInterval)
    }
  },

  onPullDownRefresh() {
    this.loadDeviceData()
    this.loadWeatherInfo()
    wx.stopPullDownRefresh()
  },

  // 更新时间
  updateTime() {
    const now = new Date()
    const timeString = now.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit'
    })
    const dateString = now.toLocaleDateString('zh-CN', {
      month: 'long',
      day: 'numeric',
      weekday: 'long'
    })
    
    this.setData({
      currentTime: timeString,
      currentDate: dateString
    })
  },

  // 加载设备数据
  async loadDeviceData() {
    try {
      // 从全局数据获取设备列表
      const devices = app.globalData.deviceList
      
      if (!devices || devices.length === 0) {
        // 如果全局数据为空，从API加载
        const deviceList = await deviceAPI.getDeviceList()
        app.globalData.deviceList = deviceList
        this.processDeviceData(deviceList)
      } else {
        this.processDeviceData(devices)
      }
    } catch (error) {
      console.error('加载设备数据失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    }
  },

  // 处理设备数据
  processDeviceData(devices) {
    // 计算统计数据
    const onlineDevices = devices.filter(device => device.status === 'online').length
    const activeDevices = devices.filter(device => 
      device.status === 'online' && device.powerState === 'on'
    ).length
    
    // 计算能耗（模拟数据）
    const energyUsage = this.calculateEnergyUsage(devices)
    
    // 检查安防状态
    const securityStatus = this.checkSecurityStatus(devices)
    
    // 检查所有灯的状态
    const lights = devices.filter(device => device.type === 'light')
    const allLightsOn = lights.length > 0 && lights.every(light => 
      light.status === 'online' && light.powerState === 'on'
    )
    
    // 获取快捷设备（收藏的设备 + 最近使用的设备）
    const quickDevices = this.getQuickDevices(devices)
    
    // 获取房间概览
    const roomOverview = this.getRoomOverview(devices)
    
    // 更新智能建议
    const suggestions = this.generateSuggestions(devices, securityStatus)
    
    this.setData({
      onlineDevices,
      activeDevices,
      energyUsage,
      securityStatus,
      allLightsOn,
      quickDevices,
      roomOverview,
      suggestions
    })
  },

  // 计算能耗
  calculateEnergyUsage(devices) {
    let totalEnergy = 0
    const activeDevices = devices.filter(device => 
      device.status === 'online' && device.powerState === 'on'
    )
    
    // 模拟能耗计算
    activeDevices.forEach(device => {
      switch(device.type) {
        case 'ac':
          totalEnergy += 1.5
          break
        case 'light':
          totalEnergy += 0.1 * (device.brightness / 100)
          break
        case 'tv':
          totalEnergy += 0.3
          break
        default:
          totalEnergy += 0.2
      }
    })
    
    return totalEnergy.toFixed(1)
  },

  // 检查安防状态
  checkSecurityStatus(devices) {
    const securityDevices = devices.filter(device => 
      device.type === 'camera' || device.type === 'sensor'
    )
    return securityDevices.some(device => 
      device.status === 'online' && device.powerState === 'on'
    )
  },

  // 获取快捷设备
  getQuickDevices(devices) {
    // 优先显示收藏设备，然后显示最近使用的设备
    const favoriteDevices = devices.filter(device => device.isFavorite)
    const recentDevices = devices
      .filter(device => !device.isFavorite)
      .sort((a, b) => (b.lastUsed || 0) - (a.lastUsed || 0))
    
    const quickDevices = [...favoriteDevices, ...recentDevices].slice(0, 6)
    
    // 更新最后使用时间
    quickDevices.forEach(device => {
      if (!device.lastUsed) {
        device.lastUsed = Date.now()
      }
    })
    
    return quickDevices
  },

  // 获取房间概览
  getRoomOverview(devices) {
    const rooms = [
      {
        id: 'livingroom',
        name: '客厅',
        icon: '/images/rooms/livingroom.png',
        background: '/images/rooms/livingroom-bg.jpg'
      },
      {
        id: 'bedroom', 
        name: '卧室',
        icon: '/images/rooms/bedroom.png',
        background: '/images/rooms/bedroom-bg.jpg'
      },
      {
        id: 'kitchen',
        name: '厨房', 
        icon: '/images/rooms/kitchen.png',
        background: '/images/rooms/kitchen-bg.jpg'
      },
      {
        id: 'bathroom',
        name: '卫生间',
        icon: '/images/rooms/bathroom.png', 
        background: '/images/rooms/bathroom-bg.jpg'
      }
    ]
    
    return rooms.map(room => {
      const roomDevices = devices.filter(device => device.room === room.id)
      const previewDevices = roomDevices.slice(0, 8) // 最多显示8个设备点
      
      return {
        ...room,
        deviceCount: roomDevices.length,
        onlineCount: roomDevices.filter(d => d.status === 'online').length,
        previewDevices
      }
    })
  },

  // 生成智能建议
  generateSuggestions(devices, securityStatus) {
    const suggestions = []
    const now = new Date()
    const hour = now.getHours()
    
    // 检查空调设置
    const acDevices = devices.filter(device => device.type === 'ac' && device.powerState === 'on')
    acDevices.forEach(ac => {
      if (ac.temperature < 24) {
        suggestions.push({
          id: `ac_${ac.id}`,
          title: '节能建议',
          description: `${ac.name}温度较低，建议调至24-26°C更节能`,
          action: 'adjust_ac',
          deviceId: ac.id
        })
      }
    })
    
    // 安防提醒
    if (!securityStatus && (hour < 8 || hour > 22)) {
      suggestions.push({
        id: 'security_reminder',
        title: '安防提醒',
        description: '夜间时段建议开启安防模式',
        action: 'enable_security'
      })
    }
    
    // 灯光提醒
    const lightsOn = devices.filter(device => 
      device.type === 'light' && device.powerState === 'on'
    )
    const emptyRoomLights = lightsOn.filter(light => {
      // 模拟房间占用检测
      return Math.random() > 0.7 // 30%的概率检测到空房间开灯
    })
    
    if (emptyRoomLights.length > 0) {
      suggestions.push({
        id: 'light_reminder',
        title: '节能提醒',
        description: `检测到${emptyRoomLights.length}个房间无人但灯光开启`,
        action: 'turn_off_lights'
      })
    }
    
    return suggestions.slice(0, 3) // 最多显示3条建议
  },

  // 加载天气信息
  async loadWeatherInfo() {
    try {
      // 模拟天气API调用
      const weatherData = await this.mockWeatherAPI()
      this.setData({
        weatherInfo: weatherData
      })
    } catch (error) {
      console.error('加载天气信息失败:', error)
    }
  },

  // 模拟天气API
  mockWeatherAPI() {
    return new Promise((resolve) => {
      setTimeout(() => {
        const conditions = ['晴朗', '多云', '小雨', '阴天']
        const randomCondition = conditions[Math.floor(Math.random() * conditions.length)]
        
        resolve({
          temperature: (20 + Math.floor(Math.random() * 15)).toString(),
          condition: randomCondition,
          humidity: (50 + Math.floor(Math.random() * 30)).toString(),
          airQuality: ['优', '良', '轻度污染'][Math.floor(Math.random() * 3)]
        })
      }, 500)
    })
  },

  // 设备状态变化监听
  onDeviceStatusChange(deviceId, status) {
    // 更新本地设备数据
    const devices = app.globalData.deviceList
    const deviceIndex = devices.findIndex(d => d.id === deviceId)
    if (deviceIndex !== -1) {
      devices[deviceIndex].status = status
      app.globalData.deviceList = devices
      this.processDeviceData(devices)
    }
  },

  // 激活快捷场景
  async activateQuickScene(e) {
    const scene = e.currentTarget.dataset.scene
    
    this.setData({
      activatingScene: true,
      activatingSceneName: scene.name
    })
    
    try {
      // 调用场景API
      await sceneAPI.activateScene(scene.id)
      
      // 更新设备状态
      await this.executeSceneDevices(scene.id)
      
      // 更新场景状态
      const quickScenes = this.data.quickScenes.map(s =>
        s.id === scene.id ? { ...s, isActive: true } : { ...s, isActive: false }
      )
      
      this.setData({ 
        quickScenes,
        activatingScene: false 
      })
      
      wx.showToast({
        title: `${scene.name} 已激活`,
        icon: 'success',
        duration: 2000
      })
      
      // 刷新设备数据
      this.loadDeviceData()
      
    } catch (error) {
      console.error('激活场景失败:', error)
      this.setData({
        activatingScene: false
      })
      wx.showToast({
        title: '激活失败',
        icon: 'error'
      })
    }
  },

  // 执行场景设备控制
  async executeSceneDevices(sceneId) {
    const app = getApp()
    const devices = app.globalData.deviceList
    
    const sceneDevices = this.getSceneDevices(sceneId, devices)
    
    for (const device of sceneDevices) {
      if (device.status !== 'offline') {
        const targetState = this.getSceneDeviceState(sceneId, device.id)
        await app.updateDeviceStatus(device.id, {
          ...device.status,
          powerState: targetState
        })
        
        // 模拟设备控制延迟
        await new Promise(resolve => setTimeout(resolve, 300))
      }
    }
  },

  // 获取场景设备
  getSceneDevices(sceneId, devices) {
    const sceneDeviceMap = {
      'home': ['light-001', 'ac-001', 'tv-001'],
      'away': ['light-001', 'light-002', 'ac-001', 'tv-001'],
      'sleep': ['light-001', 'light-002', 'ac-001'],
      'entertainment': ['light-001', 'tv-001', 'ac-001']
    }
    
    const deviceIds = sceneDeviceMap[sceneId] || []
    return devices.filter(device => deviceIds.includes(device.id))
  },

  // 获取场景设备目标状态
  getSceneDeviceState(sceneId, deviceId) {
    const stateMap = {
      'home': {
        'light-001': 'on',
        'ac-001': 'on',
        'tv-001': 'off'
      },
      'away': {
        'light-001': 'off',
        'light-002': 'off',
        'ac-001': 'off',
        'tv-001': 'off'
      },
      'sleep': {
        'light-001': 'off',
        'light-002': 'on',
        'ac-001': 'on'
      },
      'entertainment': {
        'light-001': 'on',
        'tv-001': 'on',
        'ac-001': 'on'
      }
    }
    
    return stateMap[sceneId]?.[deviceId] || 'off'
  },

  // 设备控制
  onDeviceControl(e) {
    const device = e.currentTarget.dataset.device
    if (device.status === 'offline') {
      wx.showToast({
        title: '设备离线',
        icon: 'error'
      })
      return
    }
    
    // 更新最后使用时间
    device.lastUsed = Date.now()
    
    // 跳转到设备详情页
    wx.navigateTo({
      url: `/pages/devices/devices?deviceId=${device.id}`
    })
  },

  // 设备开关切换
  async onDeviceToggle(e) {
    const deviceId = e.currentTarget.dataset.deviceId
    const isOn = e.detail.value
    
    try {
      // 调用设备控制API
      await deviceAPI.controlDevice(deviceId, {
        powerState: isOn ? 'on' : 'off'
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(deviceId, { powerState: isOn ? 'on' : 'off' })
      
      // 更新本地数据
      this.loadDeviceData()
      
      wx.showToast({
        title: isOn ? '设备已开启' : '设备已关闭',
        icon: 'success',
        duration: 1500
      })
      
    } catch (error) {
      console.error('控制设备失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      })
    }
  },

  // 房间点击
  onRoomTap(e) {
    const roomId = e.currentTarget.dataset.roomId
    wx.navigateTo({
      url: `/pages/rooms/rooms?roomId=${roomId}`
    })
  },

  // 智能建议执行
  onSuggestionAction(e) {
    const action = e.currentTarget.dataset.action
    const deviceId = e.currentTarget.dataset.deviceId
    
    switch(action) {
      case 'adjust_ac':
        this.adjustACTemperature(deviceId)
        break
      case 'enable_security':
        this.toggleSecurityMode()
        break
      case 'turn_off_lights':
        this.turnOffEmptyRoomLights()
        break
    }
    
    // 移除已执行的建议
    const suggestions = this.data.suggestions.filter(s => s.id !== e.currentTarget.dataset.id)
    this.setData({ suggestions })
  },

  // 调整空调温度
  async adjustACTemperature(deviceId) {
    try {
      await deviceAPI.controlDevice(deviceId, {
        temperature: 26
      })
      
      const app = getApp()
      await app.updateDeviceStatus(deviceId, { temperature: 26 })
      
      wx.showToast({
        title: '已调整空调温度',
        icon: 'success'
      })
      
      this.loadDeviceData()
    } catch (error) {
      wx.showToast({
        title: '调整失败',
        icon: 'error'
      })
    }
  },

  // 切换安防模式
  async toggleSecurityMode() {
    const newSecurityStatus = !this.data.securityStatus
    
    try {
      // 控制安防设备
      const securityDevices = app.globalData.deviceList.filter(device => 
        device.type === 'camera' || device.type === 'sensor'
      )
      
      for (const device of securityDevices) {
        if (device.status !== 'offline') {
          await deviceAPI.controlDevice(device.id, {
            powerState: newSecurityStatus ? 'on' : 'off'
          })
          await app.updateDeviceStatus(device.id, { 
            powerState: newSecurityStatus ? 'on' : 'off' 
          })
        }
      }
      
      this.setData({
        securityStatus: newSecurityStatus
      })
      
      wx.showToast({
        title: newSecurityStatus ? '安防模式已开启' : '安防模式已关闭',
        icon: 'success'
      })
      
      this.loadDeviceData()
      
    } catch (error) {
      console.error('切换安防模式失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      })
    }
  },

  // 关闭空房间灯光
  async turnOffEmptyRoomLights() {
    try {
      const lights = app.globalData.deviceList.filter(device => 
        device.type === 'light' && device.powerState === 'on'
      )
      
      for (const light of lights) {
        // 模拟关闭空房间的灯（随机选择一些灯关闭）
        if (Math.random() > 0.5) {
          await deviceAPI.controlDevice(light.id, { powerState: 'off' })
          await app.updateDeviceStatus(light.id, { powerState: 'off' })
        }
      }
      
      wx.showToast({
        title: '已关闭空房间灯光',
        icon: 'success'
      })
      
      this.loadDeviceData()
    } catch (error) {
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      })
    }
  },

  // 切换所有灯光
  async toggleAllLights() {
    const newState = !this.data.allLightsOn
    const lights = app.globalData.deviceList.filter(device => device.type === 'light')
    
    try {
      for (const light of lights) {
        if (light.status !== 'offline') {
          await deviceAPI.controlDevice(light.id, {
            powerState: newState ? 'on' : 'off'
          })
          await app.updateDeviceStatus(light.id, { 
            powerState: newState ? 'on' : 'off' 
          })
        }
      }
      
      this.setData({
        allLightsOn: newState
      })
      
      wx.showToast({
        title: newState ? '所有灯已打开' : '所有灯已关闭',
        icon: 'success'
      })
      
      this.loadDeviceData()
      
    } catch (error) {
      console.error('控制灯光失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      })
    }
  },

  // 添加设备
  onAddDevice() {
    wx.navigateTo({
      url: '/pages/add-device/add-device'
    })
  },

  // 跳转到场景页面
  goToScenes() {
    wx.navigateTo({
      url: '/pages/scenes/scenes'
    })
  },

  // 跳转到设备页面
  goToDevices() {
    wx.navigateTo({
      url: '/pages/devices/devices'
    })
  },

  // 跳转到房间页面
  goToRooms() {
    wx.navigateTo({
      url: '/pages/rooms/rooms'
    })
  }
})